package com.qu.waibao.account;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.alibaba.tcms.vconn.IVConnManager;
import com.qu.waibao.AppConfig;
import com.qu.waibao.MainActivity;
import com.qu.waibao.R;
import com.qu.waibao.baidu.LocationUtils;
import com.qu.waibao.utils.JumpPermissionManagement;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

public class StartActivity extends Activity {

    private Context mContext;

    private Intent intent;

    private SharedPreferences.Editor edit;

    private SharedPreferences sp;

    private boolean isFirst;

    private ArrayList<ImageView> views;

    private StartAdapter adapter;

    @BindView(R.id.viewpager)
    ViewPager viewPager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTheme(R.style.AppTheme);
        LocationUtils.startLocation();
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        sp = getSharedPreferences("data", MODE_PRIVATE);
        edit = sp.edit();
        isFirst = sp.getBoolean("isFirst", true);
        // 应用首次启动
        if (isFirst == false) {
            // 应用非首次启动
            reactToMainActivty();
            return;
        }
        setContentView(R.layout.activity_start);
        ButterKnife.bind(this);
        mContext = this;
        isPermissionsAllGranted(AppConfig.permArray, AppConfig.REQUECT_CODE_ALL);
        initView();
    }

    private void initView() {

        views = new ArrayList<>();

        ImageView view1 = new ImageView(mContext);
        view1.setImageResource(R.drawable.one);
        ImageView view2 = new ImageView(mContext);
        view2.setImageResource(R.drawable.two);
        ImageView view3 = new ImageView(mContext);
        view3.setImageResource(R.drawable.three);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);

        view1.setLayoutParams(layoutParams);
        view2.setLayoutParams(layoutParams);
        view3.setLayoutParams(layoutParams);

        view1.setScaleType(ImageView.ScaleType.FIT_XY);
        view2.setScaleType(ImageView.ScaleType.FIT_XY);
        view3.setScaleType(ImageView.ScaleType.FIT_XY);

        views.add(view1);
        views.add(view2);
        views.add(view3);
        adapter = new StartAdapter(views);

        viewPager.setAdapter(adapter);

        view3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edit.putBoolean("isFirst", false);
                edit.commit();//改变状态后一定要提交
                startActivity(new Intent(mContext, LoginActivity.class));
                finish();
            }
        });

    }

    protected boolean isPermissionsAllGranted(String[] permArray,int questCode){
        if(Build.VERSION.SDK_INT < Build.VERSION_CODES.M){
            return true;
        }
        //获得批量请求但被禁止的权限列表
        List<String> deniedPerms = new ArrayList<String>();
        for(int i=0;permArray!=null&&i<permArray.length;i++){
            if(PackageManager.PERMISSION_GRANTED != checkSelfPermission(permArray[i])){
                deniedPerms.add(permArray[i]);
            }
        }
        //进行批量请求
        int denyPermNum = deniedPerms.size();
        if(denyPermNum != 0){
            requestPermissions(deniedPerms.toArray(new String[denyPermNum]),questCode);
            return false;
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if(grantResults.length==0){
            return;
        }
        switch (requestCode) {
            case AppConfig.REQUECT_CODE_LOCATION:
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    popAlterDialog("位置","位置信息权限被禁止，将导致定位失败。。是否开启该权限？");
                }else{
                    showShortMsg("用户已经授予位置权限");
                }
                break;
            case AppConfig.REQUECT_CODE_SDCARD:
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    popAlterDialog("存储","SDCard使用权限被禁止，SDCard无法正常使用。是否开启该权限？");
                }else{
                    showShortMsg("用户已经授予SDCard使用权限");
                }
                break;
            case AppConfig.REQUECT_CODE_CAMERA:
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    popAlterDialog("相机","摄像头使用权限被禁止，拍照无法正常使用。是否开启该权限？");
                }else{
                    showShortMsg("用户已经授予相机权限");
                }
                break;
            case AppConfig.REQUECT_CODE_PHONE:
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    popAlterDialog("电话","电话权限被禁止，电话无法正常使用。是否开启该权限？");
                }else{
                    showShortMsg("用户已经授予电话权限");
                }
                break;
            case AppConfig.REQUECT_CODE_ALL:
                doPermissionAll(AppConfig.permArray,grantResults);
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions,
                        grantResults);
                break;
        }
    }

    private void doPermissionAll(String[] permissions, int[] grantResults) {
        int grantedPermNum = 0;
        int totalPermissons = permissions.length;
        int totalResults = grantResults.length;
        if(totalPermissons == 0 || totalResults == 0){
            return;
        }
        Map<String,Integer> permResults = new HashMap<String,Integer>();
        //初始化Map容器，用于判断哪些权限被授予
        for(String perm:AppConfig.permArray){
            permResults.put(perm,PackageManager.PERMISSION_DENIED);
        }
        //根据授权的数目和请求授权的数目是否相等来判断是否全部授予权限
        for(int i=0;i<totalResults;i++){
            permResults.put(permissions[i],grantResults[i]);
            if(permResults.get(permissions[i]) == PackageManager.PERMISSION_GRANTED){
                grantedPermNum ++;
            }
            Log.d("Debug","权限："+permissions[i]+"-->"+grantResults[i]);
        }
    }

    private void showShortMsg(String msg) {
        Toast.makeText(this,msg, Toast.LENGTH_SHORT).show();
    }

    private void popAlterDialog(final String msgFlg, String msgInfo) {
        new AlertDialog.Builder(StartActivity.this)
                .setTitle("使用警告")
                .setMessage(msgInfo)
                .setNegativeButton("取消", new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("设置",new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //前往应用详情界面
                        try {
                            JumpPermissionManagement.GoToSetting((Activity)mContext);
                        } catch (Exception e) {
                            showShortMsg("跳转失败");
                        }
                        dialog.dismiss();
                    }
                }).create().show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocationUtils.stopLocation();
    }
    public void reactToMainActivty(){
        intent = new Intent(StartActivity.this, MainActivity.class);
        startActivity(intent);
        finish();
    }
}
